<template>
  <div
    class="app-container"
    v-if="vis_admin"
    v-loading="loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
  >
    <div class="row">
      <DatePicker v-model="queryTime" :timevalue1="queryTime"></DatePicker>
      <el-button type="primary" style="margin-left: 15px" @click="getList"
        >查询</el-button
      >
    </div>

    <el-row class="rowClass">
      <el-col :span="24" class="card-box">
        <el-card v-show="cardShow">
          <div
            class="el-table--enable-row-hover el-table--medium"
            style="text-align: center"
          >
            <table cellspacing="0" class="contentTable" width="100%">
              <tbody>
                <tr class="tableTitleLine">
                  <th>数据统计</th>
                  <th>用户</th>
                </tr>
                <tr>
                  <td>当日</td>
                  <!-- 用户 -->
                  <td>{{ productList.newUserTheDay || "0" }}</td>
                </tr>
                <tr>
                  <td>总计</td>
                  <!-- 用户 -->
                  <td>
                    {{ productList.totalUser || "0" }}
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </el-card>
      </el-col>
      <el-col :span="24" class="card-box">
        <el-card v-show="cardShow">
          <div
            class="el-table--enable-row-hover el-table--medium"
            style="text-align: center"
          >
            <table cellspacing="0" class="contentTable" width="100%">
              <tbody>
                <tr class="tableTitleLine">
                  <th>1.9之前贡献值</th>
                  <th>1.9之后贡献值</th>
                  <th>总剩余贡献值</th>
                </tr>
                <tr>
                  <td>
                    {{ statisticalList.remainingContributionValue || "0.00" }}
                  </td>
                  <td>
                    {{
                      statisticalList.remainingContributionAllValue || "0.00"
                    }}
                  </td>
                  <td>
                    {{
                      statisticalList.remainingContributionAllValue +
                        statisticalList.remainingContributionValue || "0.00"
                    }}
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </el-card>
      </el-col>

      <el-col :span="24" class="card-box">
        <el-card v-show="cardShow">
          <div
            class="el-table--enable-row-hover el-table--medium"
            style="text-align: center"
          >
            <table cellspacing="0" class="contentTable" width="100%">
              <tbody>
                <tr class="tableTitleLine">
                  <th>运营中心提现</th>
                  <th>商家提现</th>
                </tr>
                <tr>
                  <td>
                    {{ toParseNum(productList.coreWithdrawal) || "0.00" }}
                  </td>
                  <td>
                    {{ toParseNum(productList.storeWithdrawal) || "0.00" }}
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </el-card>
      </el-col>

      <el-col :span="24" class="card-box">
        <el-card v-show="cardShow">
          <div
            class="el-table--enable-row-hover el-table--medium"
            style="text-align: center"
          >
            <table cellspacing="0" class="contentTable" width="100%">
              <tbody>
                <tr class="tableTitleLine">
                  <th>成交额</th>
                  <th>实付现金</th>
                  <th>实付通证</th>
                  <th>订单数</th>
                  <th>下单人数</th>
                  <th>提现</th>
                </tr>
                <tr>
                  <td>
                    {{ toParseNum(statisticalList.turnover) || "0.00" }}
                  </td>
                  <td>
                    {{ toParseNum(statisticalList.cashPaid) || "0.00" }}
                  </td>

                  <td>
                    {{ toParseNum(statisticalList.noticePayment) || "0.00" }}
                  </td>
                  <td>
                    {{ statisticalList.orderNumber || "0" }}
                  </td>
                  <td>
                    {{ statisticalList.orderPeopleNumber || "0" }}
                  </td>
                  <td>{{ statisticalList.szxWithdrawal || "0.00" }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12" class="card-box">
        <el-card>
          <div slot="header">
            <span>gtfy余额</span>
          </div>
          <GtfyPieChart
            ref="gtfyPieChart"
            :chartData="productList"
            v-if="show"
          ></GtfyPieChart>
        </el-card>
      </el-col>
      <el-col :span="12" class="card-box">
        <el-card>
          <div slot="header">
            <span>YKGFC余额</span>
          </div>
          <YkgfcPieChart
            ref="ykgfcPieChart"
            :chartData="productList"
            v-if="show"
          ></YkgfcPieChart>
        </el-card>
      </el-col>
    </el-row>
  </div>
  <div v-else style="text-align: center; margin-top: 10%">
    欢迎来到元宇宙商城管理系统
  </div>
</template>

<script>
import {
  // queryTotalPerformanceAndCashSales,
  // queryActualPaymentAndContribution,
  // queryConsumptionPointsAndGtfy,
  queryTotalAccelerateAndNewUser,
  queryWithdrawal,
  // queryGtfyTransformationAndAllPassPayment,
  queryGTFYBalanceAndYKGFCBalanc,
  statisticalData,
} from "@/api/ds/index";

import barChart from "../../components/wuchart/barChart.vue";
import pieChart from "../../components/wuchart/pieChart.vue";
import stackedLineChart from "../../components/wuchart/stackedLineChart.vue";

import DatePicker from "@/components/DatePicker";
import dayjs from "dayjs";
import GtfyPieChart from "../../components/wuchart/GtfyPieChart/index.vue";
import YkgfcPieChart from "../../components/wuchart/YkgfcPieChart/index.vue";

export default {
  components: {
    barChart,
    pieChart,
    stackedLineChart,
    DatePicker,
    GtfyPieChart,
    YkgfcPieChart,
  },
  name: "Server",
  data() {
    return {
      cardShow: false,
      show: false,
      // 加载层信息
      loading: true,
      // 统计贡献值（gtfy+消费积分+提现）
      commandstats: null,
      //统计gtfy+消费积分发放数据
      usedmemory: null,
      // cache信息
      cache: [],
      //参数基本信息表格
      productList: {
        queryTotalPerformance: null,
        performanceOfTheDay: null,
        totalCashSales: null,
        totalCashSalesTheDay: null,
        totalContributionValue: null,
        totalContributionValueTheDay: null,
        totalConsumptionPoints: null,
        totalConsumptionPointsTheDay: null,
        totalGtfy: null,
        totalGtfyTheDay: null,
        gtfyWithdrawal: null,
        gtfyWithdrawalTheDay: null,
      },
      //参数基本信息表格7
      productList7: {
        queryTotalPerformance: null,
        performanceOfTheDay: null,
        totalCashSales: null,
        totalCashSalesTheDay: null,
        totalContributionValue: null,
        totalContributionValueTheDay: null,
        totalConsumptionPoints: null,
        totalConsumptionPointsTheDay: null,
        totalGtfy: null,
        totalGtfyTheDay: null,
        gtfyWithdrawal: null,
        gtfyWithdrawalTheDay: null,
      },
      statisticalList: {},

      //查询参数
      queryParams: {},
      form: {},
      vis_admin: false,

      // 新增查询时间
      queryTime: [],
    };
  },
  created() {},
  computed: {
    toParseNum() {
      return (num) => {
        if (num) {
          num = num.toString();
          let index = num.indexOf(".");
          if (index !== -1) {
            num = num.substring(0, 2 + index + 1);
          } else {
            num = num.substring(0);
          }
          return parseFloat(num).toFixed(2);
        }
      };
    },
  },
  mounted() {
    this.getIndex();
    this.getList();
    // this.getStatisticalData();
  },
  methods: {
    /** 判断是不是admin用户 */
    getIndex() {
      let username = window.localStorage.getItem("username");
      if (username && username == "admin") {
        this.vis_admin = true;
      } else {
        this.vis_admin = false;
      }
    },
    /** 查询数据信息 */
    async getList() {
      this.loading = true;
      await this.getData();
      await this.getStatisticalData();
      this.loading = false;
      this.show = true;
      this.cardShow = true;
    },
    async getStatisticalData() {
      let query = {};
      if (this.queryTime.length != 0) {
        query = {
          "params[begin]": this.queryTime[0],
          "params[end]": this.queryTime[1],
        };
      } else {
        let time = this.timestampToTime(new Date().getTime());
        let beginTime = this.timestampToTime(
          new Date(new Date().toLocaleDateString()).getTime()
        );

        query = {
          "params[begin]": beginTime,
          "params[end]": time,
        };
      }

      let res = await statisticalData(query);
      console.log(res);
      this.statisticalList = res.data;
    },
    timestampToTime(timestamp) {
      var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + "-";
      var M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      var D =
        (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
      var h =
        (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      var m =
        (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
        ":";
      var s =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return Y + M + D + h + m + s;
    },

    async getData() {
      let query = {};
      query = this.addDateRange(query, this.queryTime, "");

      const funcList = [
        // queryTotalPerformanceAndCashSales,
        // queryActualPaymentAndContribution,
        // queryConsumptionPointsAndGtfy,
        queryTotalAccelerateAndNewUser,
        queryWithdrawal,
        // queryGtfyTransformationAndAllPassPayment,
        queryGTFYBalanceAndYKGFCBalanc,
      ];

      let promiseList = funcList.map((func) => {
        return new Promise(async (resolve, reject) => {
          try {
            let res = await func(query);
            if (res.code === 200) {
              this.productList = Object.assign(this.productList, res.data);
              resolve(res);
            } else {
              reject(new Error("请求错误"));
            }
          } catch (error) {
            reject(error);
          }
        });
      });

      let resList = await Promise.all(promiseList);
      console.log(
        "%c [ resList ]-440",
        "font-size:13px; background:#333333; color:#f3f3f3;",
        resList
      );
    },

    // 日期多选
    radioChanged(e) {
      let nowDay = dayjs().format("YYYY-MM-DD");
      if (e == "0") {
        // 改时间成今天
        this.queryTime = [`${nowDay} 00:00:00`, `${nowDay} 23:59:59`];
      } else if (e == "3") {
        // 改时间成今天起+前三天
        let beforeThree = dayjs().subtract(2, "day").format("YYYY-MM-DD");
        this.queryTime = [`${beforeThree} 00:00:00`, `${nowDay} 23:59:59`];
      } else if (e == "7") {
        // 改时间成今天起+前七天
        let beforeSeven = dayjs().subtract(6, "day").format("YYYY-MM-DD");

        // this.queryTime = [`${beforeSeven} 00:00:00`, `${nowDay} 23:59:59`];
        this.queryTime = [];
        this.queryTime.push(`${beforeSeven} 00:00:00`);
        this.queryTime.push(`${nowDay} 23:59:59`);
      }
      this.getList();
    },

    // 日期补零
    addDate0(time) {
      if (time.toString().length == 1) {
        time = "0" + time.toString();
      }
      return time;
    },
  },
};
// type: 'bar'：柱状/条形图
// type: 'line'：折线/面积图
// type: 'pie'：饼图
// type: 'scatter'：散点（气泡）图
// type: 'effectScatter'：带有涟漪特效动画的散点（气泡）
// type: 'radar'：雷达图
// type: 'tree'：树型图
// type: 'treemap'：树型图
// type: 'sunburst'：旭日图
// type: 'boxplot'：箱形图
// type: 'candlestick'：K线图
// type: 'heatmap'：热力图
// type: 'map'：地图
// type: 'parallel'：平行坐标系的系列
// type: 'lines'：线图
// type: 'graph'：关系图
// type: 'sankey'：桑基图
// type: 'funnel'：漏斗图
// type: 'gauge'：仪表盘
// type: 'pictorialBar'：象形柱图
// type: 'themeRiver'：主题河流
// type: 'custom'：自定义系列
</script>

<style scoped>
.row {
  display: flex;
  flex-flow: row nowrap;
  justify-content: flex-start;
  align-items: center;
}

.card-box {
  padding: 0;
}

.contentTable {
  margin: auto;
  border-collapse: collapse;
}
.tableTitleLine {
  background: lightgray;
}
.contentCard {
  background: #003b73;
  opacity: 0.9;
  border: 1px solid #2c91a0;
  color: white;
}

.radioClass {
  position: absolute;
  right: 35px;
  z-index: 99;
}
.rowClass {
  margin-top: 15px;
}
</style>
